package cn.topevery.garden.wapi.client;

import cn.topevery.garden.framework.base.IoTHandlerBase;
import cn.topevery.garden.wapi.handler.ZhongZhi_IoTHandler;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * @author ：peng.tian
 * @date ：Created in 2021/9/8 11:00
 * @description：socket消息处理
 */
public class IoTSocketClient implements Runnable {
    Socket socket;
    BufferedReader reader;
    BufferedWriter writer;
    byte [] bytes;

    public IoTSocketClient(Socket socket) {
        super();
        this.socket = socket;
    }

    private String handle(byte[] bytes) {
        String res="success!";
        List<IoTHandlerBase> ioTHandler = Arrays.asList(
                new ZhongZhi_IoTHandler()
        );
        try {
            int len = bytes.length;
            if (len != -1) {
                byte[] input = Arrays.copyOf(bytes, len);
                System.out.println("时间:" + LocalDateTime.now() + ",接收的数据:" + new String(input, 0, input.length, "UTF-8"));
                for (IoTHandlerBase handler :
                        ioTHandler) {
                    //判断接收数据的协议类型
                    if (handler.isProcess(input)) {
                        res=handler.onProcess(input);
                        break;
                    }
                }
            } else {
                System.out.println("没有数据!");
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return res;
    }

    public void run() {
        try {
            System.out.println("客户 - " + socket.getRemoteSocketAddress() + " -> 机连接成功");
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//读取客户端消息
            writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

            while ((bytes=reader.readLine().getBytes()).length>0) {
                String result = null;
                try {
                    result = handle(bytes);
                    writer.write(result);
                    writer.newLine();
                    writer.flush();
                } catch (IOException | IllegalArgumentException e) {
                    writer.write("error");
                    writer.newLine();
                    writer.flush();
                    System.out.println("发生异常");
                    try {
                        System.out.println("再次接受!");
                        result = handle(bytes);
                        writer.write(result);
                        writer.newLine();
                        writer.flush();
                    } catch (SocketTimeoutException ex) {
                        System.out.println("再次接受, 发生异常,连接关闭");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } catch (SocketException socketException) {
            socketException.printStackTrace();
            try {
                writer.close();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
